package com.jackrain.nea.fc.dl.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.nea.common.QueryCpUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.ViewBatchUpdateCmd;
import com.jackrain.nea.fc.dl.mapper.ViewBatchUpdateMaper;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class ViewBatchUpdateCmdImpl extends CommandAdapter implements ViewBatchUpdateCmd {

    @Autowired
    QueryCpUtil postQueryEvemt;

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {
        ValueHolder vh = new ValueHolder();
        ViewBatchUpdateMaper viewBatchUpdateMaper = ApplicationContextHandle.getBean(ViewBatchUpdateMaper.class);
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        if (null == param || (!param.containsKey("IDS")) || param.getJSONArray("IDS").size() <= 0) {
            throw new NDSException("参数格式错误！");
        }
        log.info("ViewBatchUpdateCmdImpl--param-->{}",param);

//        log.debug("----------拣货装箱单发出查询参数----------" + param);
//        JSONArray dataArray = param.getJSONArray("IDS");

//        List<HashMap> mapList = new ArrayList<>();
//
//        Object[] list = (Object[]) param.getJSONArray("IDS").toArray();
//        StringBuilder sb = new StringBuilder();
//        for (Object num : list) {
//            sb.append(num).append(",");
//        }
//        sb.deleteCharAt(sb.length() - 1);

        String type = param.getString("type");
        JSONArray idArray = param.getJSONArray("IDS");
        JSONArray resultArray = new JSONArray();

        for (int i = 0; i < idArray.size(); i++) {

            HashMap dataMap = new HashMap();
            Long id = idArray.getLong(i);
            if ("dlsource".equals(type)) {
                dataMap = viewBatchUpdateMaper.selComBatchUpdate(id);
            } else {
                dataMap = viewBatchUpdateMaper.selBatchUpdate(id);
            }
            JSONObject mainJo = new JSONObject(dataMap);
            JSONObject dataJo = new JSONObject();
            Long origId = mainJo.getLong("CP_C_ORIG_ID");
            Long destId = mainJo.getLong("CP_C_DEST_ID");
//            跨库查询
            JSONObject origData = queryCp(origId, "CP_C_STORE");
            JSONObject destData = queryCp(destId, "CP_C_STORE");

            dataJo.put("orderId", mainJo.getString("BILL_NO"));
            String oriNature = origData.getString("STORENATURE");
            String destNature = destData.getString("STORENATURE");

            if ("WH".equals(oriNature) && "STO".equals(destNature)) {//仓到店
                dataJo.put("orderType", 1);
            }
            if ("STO".equals(oriNature) && "WH".equals(destNature)) {//店到仓
                dataJo.put("orderType", 3);
            }
            if ("STO".equals(oriNature) && "STO".equals(destNature)) {//店到店
                dataJo.put("orderType", 4);
            }
            if ("WH".equals(oriNature) && "WH".equals(destNature)) {//仓到仓
                dataJo.put("orderType", 5);
            }
            dataJo.put("sendAddress", origData.getString("ENAME"));
            dataJo.put("sendAddressCode", origData.getString("ECODE"));

            dataJo.put("destination", destData.getString("ENAME"));
            dataJo.put("destinationCode", destData.getString("ECODE"));
            if ("dlsource".equals(type)) {
                //包数量
                dataJo.put("packageNum", mainJo.getString("PACKAGE_COUNT"));
                Long ids = (Long) mainJo.get("ID");
                HashMap hashMap = viewBatchUpdateMaper.selStDaLog(ids);
                //转换时间格式
                Date sendTime = (Date) hashMap.get("SEND_TIME");
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //发出日期
                dataJo.put("sendOutTime",format.format(sendTime.getTime()));
                //计划出库日期
                dataJo.put("outboundDate",hashMap.get("BILL_DATE"));
                //是否标准箱
                dataJo.put("standardBox", 0);
                //补货周期
                dataJo.put("replenishmentCycle", hashMap.get("CYCLE_DAYS"));
                //物流批次
                dataJo.put("batchNo", hashMap.get("LOGISTICS"));
                //原始单号
                List<HashMap> billNos = viewBatchUpdateMaper.selItemBillNo(ids);
                if(billNos.size()<2){
                    dataJo.put("orginalOrderIds", billNos.get(0).get("DL_B_TRAN_BILL_NO"));
                }else{
                    String billno = "";
                    for(int j=0;j<billNos.size();j++){
                        if(j==(billNos.size()-1)){
                            billno = billno + billNos.get(j).get("DL_B_TRAN_BILL_NO");
                        }else{
                            billno = billno + billNos.get(j).get("DL_B_TRAN_BILL_NO") +",";
                        }
                    }
                    dataJo.put("orginalOrderIds",billno);
                }
                //物料
                int sumqty = mainJo.getIntValue("SKU_NUMBER");
                //件数
                dataJo.put("packagePieces", sumqty);
            } else {
                dataJo.put("departureTime", mainJo.getString("BILL_DATE"));
                //转换时间格式
                Date sendTime = (Date) mainJo.get("SEND_TIME");
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                dataJo.put("sendOutTime",format.format(sendTime.getTime()));
                dataJo.put("outboundDate",mainJo.get("BILL_DATE"));
                dataJo.put("replenishmentCycle", mainJo.getString("CYCLE_DAYS"));
                dataJo.put("batchNo", mainJo.getString("LOGISTICS"));
                String standarBox =  mainJo.getString("VARCHAR5");
                if("N".equals(standarBox)){
                    dataJo.put("standardBox",0);
                }
                if("Y".equals(standarBox)){
                    dataJo.put("standardBox",1);
                }
                List<HashMap> bill_no = viewBatchUpdateMaper.selBillNo(id);
                if(bill_no.size()<2){
                    dataJo.put("orginalOrderIds", bill_no.get(0).get("BILL_NO"));
                }else{
                    String billno = "";
                    for(int j=0;j<bill_no.size();j++){
                        if(j==(bill_no.size()-1)){
                            billno = billno + bill_no.get(j).get("BILL_NO");
                        }else{
                            billno = billno + bill_no.get(j).get("BILL_NO") +",";
                        }
                    }
                    dataJo.put("orginalOrderIds",billno);
                }
                BigDecimal sumQtyOut = BigDecimal.ZERO;
                sumQtyOut = mainJo.getBigDecimal("SUM_QTY_OUT");
                int sumqty = sumQtyOut.intValue();
                dataJo.put("packagePieces", sumqty);
                //追货宝编号
                dataJo.put("trace_device_no", mainJo.getString("VARCHAR2"));
            }
            resultArray.add(dataJo);
        }
        log.debug("ViewBatchUpdateCmdImpl--FTM-->{}",resultArray);
//        log.debug("---------------------FTM" + resultArray);
        if (resultArray == null || resultArray.size() <= 0) {

            vh.put("code", 2);
            vh.put("message", "无相应数据!");
            return vh;

        }
        vh.put("data", resultArray);
        vh.put("code", 0);
        vh.put("message", "查询成功");
        return vh;
    }

    /**
     * list转jsonarray
     *
     * @param mapList
     * @return jsonArray
     */
    public JSONArray listToJsonarray(List<HashMap> mapList) {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < mapList.size(); i++) {
            HashMap map = (HashMap) mapList.get(i);
            JSONObject jsonObject = new JSONObject(map);
            JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(jsonObject, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
            jsonArray.add(param);
        }
        return jsonArray;
    }

    /**
     * 跨库查询
     *
     * @param id
     * @param tableName
     */
    public JSONObject queryCp(Long id, String tableName) {

        JSONObject whereJo = new JSONObject();
        whereJo.put("ID", id);
        JSONObject result = postQueryEvemt.queryCP(tableName, "ENAME,ECODE,STORENATURE", whereJo);
        return result;
    }
}